/**
 * 获取访问的客户端版本
 * @returns {boolean} true 微信中打开
 */
export function inWeCaht() {
	// 不加window部分Android机会显示不了提示图，即判断不了是否是微信
    const userAgent = window.navigator.userAgent.toLowerCase()
	
    if (userAgent.match(/MicroMessenger/i) == "micromessenger") {
        return true
    }
    return false
}

/**
 * 获取设备所处系统
 * @returns {{systemMobile: string, equipment: string}}
 */
export function getSystem() {
    // 设备型号和系统
    let system = {"equipment": "", "systemMobile": ""}
    const app = navigator.appVersion;

    //根据括号进行分割
    const left = app.indexOf('(');
    const right = app.indexOf(')');
    const str = app.substring(left + 1, right);
    const Str = str.split(";");

    //手机型号--苹果 iPhone
    const Mobile_Iphone = Str[0];

    //手机型号--安卓
    const Mobile_Android = Str[2];

    // 红米手机等特殊型号处理 匹配字符
    const res = /Android/;
    const result = res.test(Mobile_Android);
    if (Mobile_Iphone.indexOf('iPhone') >= 0) {
        system.equipment = "iPhone"
        system.systemMobile = Str[1].substring(4, Str[1].indexOf('like'))
        return system
    }
    if (Mobile_Iphone === 'Linux') {
        system.equipment = "Android"
        if(result){
            system.systemMobile = Str[2]
            return system
        }
        system.systemMobile = Str[1]
        return system
    }
}


/**
 * A 标签下载文件
 * @param url
 */
export function downloadFile(url) {
    const link = document.createElement('a');
    link.href = url;
    link.download = ''; // 可以设置文件名
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

/**
 * Blob 方式下载
 * @param url
 * @returns {Promise<void>}
 */
export async function downloadFileByBlob(url,fileName) {
    try {
        const response = await fetch(url);
        const blob = await response.blob();
        const urlObject = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = urlObject;
        link.download = fileName; // 设置文件名
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(urlObject); // 清理临时URL
    } catch (error) {
        console.error('Error downloading file:', error);
    }
}